﻿/*
 * Copyright (c) Martin Kinkelin
 *
 * See the "License.txt" file in the root directory for infos
 * about permitted and prohibited uses of this code.
 */

using System;
using System.Windows.Forms;
using Microsoft.Win32.TaskScheduler;

namespace Jarf
{
	/// <summary>
	/// Allows scheduling of a backup task on Windows.
	/// </summary>
	public partial class ScheduleDialog : BaseDialog
	{
		private TaskService _service;
		private BackupTask _backupTask;
		private Task _task;



		public ScheduleDialog(BackupTask backupTask)
		{
			if (backupTask == null)
				throw new ArgumentNullException("backupTask");

			_service = new TaskService();
			_backupTask = backupTask;

			InitializeComponent();

			// search for an appropriate task
			foreach (Task task in _service.RootFolder.Tasks)
			{
				for (int i = 0; i < task.Definition.Actions.Count; i++)
				{
					ExecAction execAction = task.Definition.Actions[i] as ExecAction;
					if (execAction != null &&
						string.Compare(execAction.Path, Application.ExecutablePath, true) == 0 &&
						execAction.Arguments == _backupTask.Guid)
					{
						_task = task;

						checkBox1.Checked = _task.Enabled;

						if (_task.Definition.Triggers.Count == 1)
						{
							Trigger trigger = _task.Definition.Triggers[0];

							if (trigger is DailyTrigger)
								intervalComboBox.SelectedIndex = 0;
							else if (trigger is WeeklyTrigger)
								intervalComboBox.SelectedIndex = 1;
							else if (trigger is MonthlyDOWTrigger)
								intervalComboBox.SelectedIndex = 2;

							timeMaskedTextBox.Text = trigger.StartBoundary.ToString("t");
						}

						HasChanged = false;

						return;
					}
				}
			}

			intervalComboBox.SelectedIndex = 1;
			timeMaskedTextBox.Text = DateTime.Now.ToString("t");

			HasChanged = false;
		}

		private void checkBox1_CheckedChanged(object sender, EventArgs e)
		{
			intervalComboBox.Enabled = timeMaskedTextBox.Enabled = checkBox1.Checked;
			HasChanged = true;
		}

		private void control_Changed(object sender, EventArgs e)
		{
			HasChanged = true;
		}

		protected override bool ApplyChanges()
		{
			if (!checkBox1.Checked)
			{
				if (_task != null)
					_service.RootFolder.DeleteTask(_task.Name);

				return true;
			}

			TaskDefinition definition = _service.NewTask();

			definition.RegistrationInfo.Description = string.Format("Backs up \"{0}\" to \"{1}\".",
				_backupTask.Source, _backupTask.Destination);

			definition.Actions.Add(new ExecAction(Application.ExecutablePath,
				_backupTask.Guid, Application.StartupPath));

			if (intervalComboBox.SelectedIndex == 0)
				definition.Triggers.Add(new DailyTrigger());
			else if (intervalComboBox.SelectedIndex == 1)
				definition.Triggers.Add(new WeeklyTrigger());
			else
				definition.Triggers.Add(new MonthlyDOWTrigger());

			TimeSpan time;
			if (!TimeSpan.TryParse(timeMaskedTextBox.Text, out time))
			{
				MessageBox.Show("Please enter a valid time.", "Invalid time",
					MessageBoxButtons.OK, MessageBoxIcon.Error);
				timeMaskedTextBox.Focus();
				return false;
			}

			DateTime sb = definition.Triggers[0].StartBoundary;
			definition.Triggers[0].StartBoundary = definition.Triggers[0].StartBoundary.Date + time;

			if (_task != null)
				_service.RootFolder.DeleteTask(_task.Name);

			// set some advanced settings under Vista
			if (_service.HighestSupportedVersion.Major >= 2)
			{
				definition.Settings.AllowHardTerminate = false;
				definition.Settings.StopIfGoingOnBatteries = false;
				definition.Settings.StartWhenAvailable = true;
			}

			definition.Principal.LogonType = TaskLogonType.InteractiveToken;
			_service.RootFolder.RegisterTaskDefinition(string.Format("Jarf ({0})", _backupTask.Guid), definition,
				TaskCreation.Create, null, null, TaskLogonType.InteractiveToken, null);

			return true;
		}
	}
}
